import { fileURLToPath, URL } from 'node:url';
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import vueDevTools from 'vite-plugin-vue-devtools';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
import sass from 'sass';

export default defineConfig(({ mode }) => {
	const isProduction = mode === 'production';

	return {
		// 依赖预构建配置
		optimizeDeps: {
			include: ['@icon-park/vue-next/es/icons/User']
		},
		// 插件配置
		plugins: [
			vue(),
			vueDevTools(),
			AutoImport({
				resolvers: [
					ElementPlusResolver(),
				],
			}),
			Components({
				resolvers: [
					ElementPlusResolver(),
				],
			}),
		],
		// 路径别名配置
		resolve: {
			alias: {
				'@': fileURLToPath(new URL('./src', import.meta.url))
			},
		},
		// 开发服务器配置
		server: {
			proxy: {
				'/api': {
					target: 'http://localhost:8080',
					changeOrigin: true,
					rewrite: (path) => path.replace(/^\/api/, '')
				}
			}
		},
		// CSS 预处理器配置
		css: {
			preprocessorOptions: {
				sass: {
					implementation: sass,
				},
			},
		},
		// 构建配置
		build: {
			minify: isProduction ? 'esbuild' : false, // 生产环境压缩代码
			chunkSizeWarningLimit: 1500, // 调整块大小警告限制
			rollupOptions: {
				output: {
					// 手动分割代码块
					manualChunks(id) {
						if (id.includes('node_modules')) {
							return id.toString().split('node_modules/')[1].split('/')[0].toString();
						}
					}
				}
			}
		},
		// esbuild 配置
		esbuild: {
			drop: isProduction ? ['console', 'debugger'] : [] // 生产环境移除 console 和 debugger
		}
	};
});